<template>
  <div class="app-container">
    <el-card v-if="activity" class="activity-detail">
      <div class="activity-header">
        <h1>{{ activity.activityName }}</h1>
        <el-tag :type="statusTagType(activity.status)" size="large">
          {{ statusLabel(activity.status) }}
        </el-tag>
      </div>

      <el-divider />

      <el-row :gutter="20">
        <el-col :span="12">
          <el-descriptions title="活动基本信息" :column="1" border>
            <el-descriptions-item label="活动ID">{{ activity.activityId }}</el-descriptions-item>
            <el-descriptions-item label="活动名称">{{ activity.activityName }}</el-descriptions-item>
            <el-descriptions-item label="活动类型">
              <el-tag :type="typeTagType(activity.activityType)">
                {{ typeLabel(activity.activityType) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="开始时间">{{ activity.startTime }}</el-descriptions-item>
            <el-descriptions-item label="结束时间">{{ activity.endTime }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ activity.createTime }}</el-descriptions-item>
            <el-descriptions-item label="更新时间">{{ activity.updateTime }}</el-descriptions-item>
            <el-descriptions-item label="活动描述">{{ activity.activityDesc }}</el-descriptions-item>
          </el-descriptions>
        </el-col>

        <el-col :span="12">
          <el-card class="poster-card">
            <template #header>
              <span>活动海报</span>
            </template>
            <div class="poster-container">
              <el-image v-if="activity.posterUrl" :src="activity.posterUrl" :preview-src-list="[activity.posterUrl]"
                fit="contain" class="poster-image" />
              <div v-else class="no-poster">
                暂无海报
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-divider />

      <div class="sku-section">
        <h2>活动商品</h2>
        <el-button @click="goBack">返回</el-button>
        <el-button type="primary" @click="handleAddProduct" icon="Plus">添加商品</el-button>

        <br /><br />

        <el-table :data="activity.skuList" border style="width: 80%">
          <el-table-column prop="skuName" label="商品名称" max-width="50">
            <template #default="scope">
              <div class="sku-name">{{ scope.row.skuName }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="code" label="SKU编码" width="180" />
          <el-table-column prop="price" label="原价" width="130">
            <template #default="scope">
              ${{ scope.row.price }}
            </template>
          </el-table-column>
          <el-table-column prop="activityPrice" label="活动价" width="190">
            <template #default="scope">
              <el-input 
                v-model.number="scope.row.activityPrice" 
                size="small"
                style="width: 100px;"
              />
              <el-button 
                type="primary" 
                link 
                @click="handlePriceChange(scope.row)"
                icon="Check"
                style="margin-left: 5px;"
              >
                更新
              </el-button>
            </template>
          </el-table-column>
          <el-table-column prop="stock" label="库存" width="130" />

          <!-- <el-table-column label="商品图片" width="120">
            <template #default="scope">
              <el-image 
                v-if="scope.row.image" 
                :src="scope.row.image" 
                :preview-src-list="[scope.row.image]"
                fit="cover"
                style="width: 80px; height: 80px; border-radius: 4px;"
              />
              <span v-else>无图片</span>
            </template>
          </el-table-column> -->

          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button 
                type="danger" 
                link 
                @click="handleRemoveProduct(scope.row)"
                icon="Delete"
              >
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 添加商品对话框 -->
      <el-dialog title="添加活动商品" v-model="addProductDialog.visible" width="600px" append-to-body>
        <el-form ref="addProductFormRef" :model="addProductDialog.form" :rules="addProductDialog.rules"
          label-width="100px">

          <el-form-item label="商品SKU" prop="skuId">
            <el-select v-model="addProductDialog.form.skuId" placeholder="请选择商品SKU" filterable remote
              :remote-method="searchSku" :loading="addProductDialog.loading" style="width: 100%">
              <el-option v-for="item in skuOptions" :key="item.id" :label="item.name" :value="item.id">
                <span style="float: left">{{ item.name }}</span>
                <!-- <span style="float: right; color: #8492a6; font-size: 13px">￥{{ item.price }}</span> -->
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="活动价格" prop="price">
            <el-input-number v-model="addProductDialog.form.price" :precision="2" :step="0.01" :min="0"
              controls-position="right" style="width: 100%" />
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="cancelAddProduct">取 消</el-button>
            <el-button type="primary" @click="submitAddProduct">确 定</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>

    <div v-else class="loading-container">
      <el-skeleton v-if="loading" :rows="10" animated />
      <el-empty v-else description="活动不存在" />
    </div>
  </div>
</template>

<script setup name="ActivityDetail">
import { ref, onMounted, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getCurrentInstance } from 'vue'
import { getProductActivity, addActivityProduct, deleteActivityProduct, updateActivityProductPrice } from '@/api/market/activity'
import { getSkuNameList } from '@/api/product/sku'

const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance()

const activity = ref(null)
const loading = ref(true)

// 活动状态标签类型映射
const statusTagType = (status) => {
  const statusMap = {
    '0': 'warning',  // 未开始
    '1': 'success',  // 进行中
    '2': 'info'      // 已结束
  }
  return statusMap[status] || ''
}

// 活动状态标签文本映射
const statusLabel = (status) => {
  const statusMap = {
    '0': '未开始',
    '1': '进行中',
    '2': '已结束'
  }
  return statusMap[status] || '未知状态'
}

// 活动类型标签类型映射
const typeTagType = (type) => {
  const typeMap = {
    '1': 'primary',  // 折扣活动
    '2': 'success'   // 满减活动
  }
  return typeMap[type] || ''
}

// 活动类型标签文本映射
const typeLabel = (type) => {
  const typeMap = {
    '1': '折扣活动',
    '2': '满减活动'
  }
  return typeMap[type] || '未知类型'
}

// 添加商品对话框状态
const addProductDialog = reactive({
  visible: false,
  loading: false,
  form: {
    skuId: null,
    price: undefined
  },
  rules: {
    skuId: [{ required: true, message: '请选择商品SKU', trigger: 'change' }],
    price: [{ required: true, message: '请输入活动价格', trigger: 'blur' }]
  }
})

// SKU选项
const skuOptions = ref([])

// 获取活动详情
const fetchActivityDetail = async (id) => {
  try {
    loading.value = true
    const response = await getProductActivity(id)
    activity.value = response.data

    // 确保数据类型正确
    if (activity.value) {
      activity.value.activityType = activity.value.activityType?.toString()
      activity.value.status = activity.value.status?.toString()
    }
  } catch (error) {
    console.error('获取活动详情失败:', error)
    proxy.$modal.msgError('获取活动详情失败')
  } finally {
    loading.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 编辑活动
// const editActivity = () => {
//   router.push(`/market/activity/edit/${activity.value.activityId}`)
// }

// 处理添加商品按钮点击
const handleAddProduct = () => {
  addProductDialog.visible = true
  addProductDialog.form = {
    skuId: null,
    price: undefined
  }
  // 初始化加载SKU列表
  searchSku('')
}

// 搜索SKU
const searchSku = async (query) => {
  addProductDialog.loading = true
  try {
    const params = {
      pageNum: 1,
      pageSize: 100,
      skuName: query
    }
    const response = await getSkuNameList(params)
    skuOptions.value = response.data.map(item => ({
      id: item.id,
      name: item.skuName
    }))
  } catch (error) {
    console.error('获取SKU列表失败:', error)
    proxy.$modal.msgError('获取SKU列表失败')
  } finally {
    addProductDialog.loading = false
  }
}

// 取消添加商品
const cancelAddProduct = () => {
  addProductDialog.visible = false
  proxy.resetForm('addProductFormRef')
}

// 提交添加商品
const submitAddProduct = () => {
  proxy.$refs.addProductFormRef.validate(async (valid) => {
    if (valid) {
      try {
        const params = {
          skuId: addProductDialog.form.skuId,
          price: addProductDialog.form.price
        }

        await addActivityProduct(activity.value.activityId, params)
        proxy.$modal.msgSuccess('添加商品成功')
        cancelAddProduct()
        // 重新加载活动详情
        fetchActivityDetail(activity.value.activityId)
      } catch (error) {
        console.error('添加商品失败:', error)
        proxy.$modal.msgError('添加商品失败')
      }
    }
  })
}

// 处理价格变更
const handlePriceChange = async (row) => {
  try {
    // 检查价格是否有效
    if (row.activityPrice === null || row.activityPrice === undefined || row.activityPrice < 0) {
      proxy.$modal.msgError('请输入有效的价格')
      return
    }
    
    const response = await updateActivityProductPrice(activity.value.activityId, row.id, row.activityPrice)
    if (response.code === 200) {
      proxy.$modal.msgSuccess('价格更新成功')
    } else {
      proxy.$modal.msgError('价格更新失败: ' + response.msg)
    }
  } catch (error) {
    console.error('更新价格失败:', error)
    proxy.$modal.msgError('价格更新失败: ' + (error.message || error))
  }
}

// 处理移除商品
const handleRemoveProduct = async (row) => {
  try {
    await proxy.$modal.confirm(`确定要从活动中移除商品 "${row.skuName}" 吗？`)
    const response = await deleteActivityProduct(activity.value.activityId, row.id)
    if (response.code === 200) {
      proxy.$modal.msgSuccess('移除商品成功')
      // 重新加载活动详情
      fetchActivityDetail(activity.value.activityId)
    } else {
      proxy.$modal.msgError('移除商品失败: ' + response.msg)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('移除商品失败:', error)
      proxy.$modal.msgError('移除商品失败: ' + (error.message || error))
    }
  }
}

onMounted(() => {
  const activityId = route.params.id
  if (activityId) {
    fetchActivityDetail(activityId)
  } else {
    loading.value = false
  }
})
</script>

<style lang="scss" scoped>
.activity-detail {
  .activity-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h1 {
      margin: 0;
      font-size: 24px;
      font-weight: bold;
    }
  }

  .poster-card {
    height: 100%;

    .poster-container {
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 300px;

      .poster-image {
        max-width: 100%;
        max-height: 300px;
      }

      .no-poster {
        color: #909399;
        font-size: 14px;
      }
    }
  }

  .sku-section {
    margin-top: 20px;

    .sku-name {
      font-weight: 500;
    }
  }
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}
</style>